package com.example.lenovo.sbns.Activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.example.lenovo.sbns.R;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;




public class indexPage extends Fragment {

    private ViewFlipper viewFlipper;
    private GridView gridView;
    private SimpleAdapter simpleAdapter;
    private MyAdapter myAdapter;
    private List<Map<String,Object>> list;
    private Drawable productimage;
    private int ResId[] = {R.mipmap.picone,R.mipmap.pictwo,R.mipmap.picthree};





    /**
     * 自动计算GridView高度
     * @param listView
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public static void setListViewHeightBasedOnChildren(GridView listView) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = 2;// listView.getNumColumns();
        int totalHeight = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; i < listAdapter.getCount(); i += col) {
            System.out.println(listAdapter.getCount());
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }

        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置参数
        listView.setLayoutParams(params);
    }





    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        System.out.println("07");
        View view = inflater.inflate(R.layout.fragment_index_page, container, false);
        System.out.println("06");


        //连接数据库
        AVOSCloud.initialize(getActivity(), "Po6OudEc9QxRgv1qcussxBxi-gzGzoHsz", "EFNsW7y5aXtKMkpU50xyhHNk");

        gridView = (GridView) view.findViewById(R.id.Grid);


        /*查询远端数据库数据*/
        final AVQuery<AVObject> query = new AVQuery<>("ProductInfo");
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(final List<AVObject> listr, AVException e) {
                List<AVObject> priorityEqualsZeroTodos = listr;// 符合 priority = 1 的 Todo 数组
                final String[] IdLine = new String[priorityEqualsZeroTodos.size()];
                /*动态生成产品表格*/
                list = new ArrayList<Map<String, Object>>();
                /*List数组赋值*/
                for (int i = 0; i < priorityEqualsZeroTodos.size(); i++) {
                    final Map<String, Object> map = new HashMap<String, Object>();
                    final int Flag = i;
                    final Handler handler = new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                            map.put("image", (Drawable) msg.obj);
                            list.add(map);
                            myAdapter = new MyAdapter(list, getActivity());
                            gridView.setAdapter(myAdapter);
                            setListViewHeightBasedOnChildren(gridView);
                        }
                    };
                    final String url = priorityEqualsZeroTodos.get(i).getString("productImage");
                    // image
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            //post() is quite important,update pictures in UI main thread
                            Drawable drawable = loadImageFromNetwork(url);
                            Message message = handler.obtainMessage(1, drawable);
                            handler.sendMessage(message);
                        }
                    }).start();  //线程启动

                    map.put("declear", priorityEqualsZeroTodos.get(i).getString("productname"));
                    /*map.put("image",productimage);*/
                    map.put("price", priorityEqualsZeroTodos.get(i).getString("productprice"));
                    map.put("time", priorityEqualsZeroTodos.get(i).getString("productdeclear"));
                    map.put("ProductID", priorityEqualsZeroTodos.get(i).getObjectId());
                    IdLine[i] = priorityEqualsZeroTodos.get(i).getString("objectId");
                    /*list.add(map);*/
                }
                for (int m = 0; m < list.size(); m++) {
                    System.out.println(list.get(m));
                }
                /*String[] from = {"image", "declear", "price", "time"};
                int[] to = {R.id.ImageTag, R.id.DeclearTag, R.id.PriceTag, R.id.TimeTag};

                simpleAdapter = new SimpleAdapter(getActivity(), list, R.layout.grid_item, from, to);
                gridView.setAdapter(simpleAdapter);
                setListViewHeightBasedOnChildren(gridView);*/

                /*myAdapter = new MyAdapter(list,getActivity());
                gridView.setAdapter(myAdapter);
                setListViewHeightBasedOnChildren(gridView);*/
                /*绑定点击触发器*/
                gridView.setOnItemClickListener(
                        new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Intent intent = new Intent();
                                intent.setClass(getActivity(), product_info.class);
                                intent.putExtra("ProductID", list.get(position).get("ProductID").toString());
                                startActivity(intent);
                            }
                        }
                );

            }

        });



        /*动态生成图片跑马灯式界面*/
        viewFlipper = (ViewFlipper) view.findViewById(R.id.Flipper);
        for(int i = 0;i < ResId.length;i++){
            viewFlipper.addView(getImageView(ResId[i]));
        }
        viewFlipper.setInAnimation(getActivity(), R.anim.left_in);
        viewFlipper.setOutAnimation(getActivity(), R.anim.left_out);
        viewFlipper.setFlipInterval(5000);
        viewFlipper.startFlipping();



        return view;

    }




    /**
     * 布局匹配类
     */
    public class ViewHolder{

        public ImageView imageView;
        public TextView declearView;
        public TextView priceView;
        public TextView timeView;

    }

    /**
     * GridView数据适配器
     */
    public class MyAdapter extends BaseAdapter {

        private LayoutInflater layoutInflater;
        private List<Map<String,Object>> list;


        public MyAdapter(List<Map<String, Object>> data, Context context) {
            super();
            layoutInflater = LayoutInflater.from(context);
            list = data;
        }

        @Override
        public int getCount() {
            if(list != null){
                return list.size();
            }
            else {
                return 0;
            }
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder = new ViewHolder();
            if(convertView == null){
                convertView = layoutInflater.inflate(R.layout.grid_item,null);
                viewHolder = new ViewHolder();
                viewHolder.imageView = (ImageView) convertView.findViewById(R.id.ImageTag);
                viewHolder.declearView = (TextView) convertView.findViewById(R.id.DeclearTag);
                viewHolder.priceView = (TextView) convertView.findViewById(R.id.PriceTag);
                viewHolder.timeView = (TextView) convertView.findViewById(R.id.TimeTag);
                convertView.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.imageView.setImageDrawable((Drawable) list.get(position).get("image"));
            viewHolder.declearView.setText((String) list.get(position).get("time"));
            viewHolder.priceView.setText((String) list.get(position).get("price"));
            viewHolder.timeView.setText((String) list.get(position).get("declear"));
            return convertView;
        }
    }

    private ImageView getImageView(int resourceId){
        ImageView imageView = new ImageView(getActivity());
        imageView.setBackgroundResource(resourceId);
        return imageView;
    }


    //download image from network using @urladdress
    private Drawable loadImageFromNetwork(String urladdr) {
        // TODO Auto-generated method stub
        Drawable drawable = null;
        try{
            //judge if has picture locate or not according to filename
            drawable = Drawable.createFromStream(new URL(urladdr).openStream(), "image.jpg");
        }catch(IOException e){
            Log.d("test",e.getMessage());
        }
        if(drawable == null){
            Log.d("test","null drawable");
        } else {
            Log.d("test","not null drawable");
        }
        return drawable;
    }



}


